<template>
  <div ref="chartContainer" class="chartContainer"></div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { SciChartSurface, NumericAxis, FastLineRenderableSeries, XyDataSeries } from 'scichart';

export default {
  name: 'SciChartWrapper',
  props: {
    licenseKey: {
      type: String,
      required: true,
      default: 'YOUR_COMMUNITY_LICENSE_KEY', // 替换为你的社区版密钥
    },
    data: {
      type: Array,
      required: true,
      default: () => [], // 示例数据格式: [{ x: 0, y: 0 }, { x: 1, y: 1 }]
    },
  },
  setup(props) {
    const chartContainer = ref(null);
    let sciChartSurface = null;

    // 初始化 SciChart
    const initSciChart = async () => {
      try {
        // 设置许可证密钥
        SciChartSurface.setRuntimeLicenseKey(props.licenseKey);

        // 等待 SciChart 资源加载
        await SciChartSurface.ready();

        // 创建图表表面
        sciChartSurface = new SciChartSurface(chartContainer.value);

        // 创建 X 轴和 Y 轴
        const xAxis = new NumericAxis(sciChartSurface.xAxes);
        const yAxis = new NumericAxis(sciChartSurface.yAxes);

        // 创建数据系列
        const dataSeries = new XyDataSeries({
          xValues: props.data.map(item => item.x),
          yValues: props.data.map(item => item.y),
        });

        // 创建渲染系列
        const renderSeries = new FastLineRenderableSeries({
          dataSeries,
          stroke: '#4f8ff7',
          strokeThickness: 2,
        });

        // 添加系列和轴到图表
        sciChartSurface.renderableSeries.add(renderSeries);
        sciChartSurface.xAxes.add(xAxis);
        sciChartSurface.yAxes.add(yAxis);

        // 自动调整范围
        sciChartSurface.zoomExtents();
      } catch (error) {
        console.error('SciChart 初始化失败:', error);
      }
    };

    // 销毁图表
    const disposeSciChart = () => {
      if (sciChartSurface) {
        sciChartSurface.dispose();
        sciChartSurface = null;
      }
    };

    // 生命周期钩子
    onMounted(initSciChart);
    onBeforeUnmount(disposeSciChart);

    return { chartContainer };
  },
};
</script>
